import Flutter
import UIKit


public class SwiftImPlugin_new: NSObject, FlutterPlugin,IMsgCallBack {
    
     public static var channel:FlutterMethodChannel!;
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        print("this is register")
        channel = FlutterMethodChannel(name: "com.quwan.imlib/flutter_im_plugin", binaryMessenger: registrar.messenger())
        let instance = SwiftImPlugin_new()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
   
    /**
       * 调用flutter方法
       *
       * @param method    方法名
       * @param arguments 传递的参数
       */
    
  private func invokeMethod( method:String, arguments:Any) {
    if SwiftImPlugin_new.channel != nil {
            SwiftImPlugin_new.channel.invokeMethod(method, arguments: arguments)
        }
    }
    
  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    
//    print("this is handle")
    let methodName = call.method;
    let arguments = call.arguments as? Dictionary<String,AnyObject>

    
    switch methodName {
    case "log":
        //xlog日志打印
//        let level = arguments?["level"]
//        let tag = arguments?["tag"]
//        let msg = arguments?["msg"]
//        let isIMLog = MsgUtils.toBoolValue(number: (arguments?["isIMLog"] != nil));
//        XLogWrapper.getInstance().printLog(isIMLog: isIMLog, level: level as! String, tag: tag as! String, log: msg as! String)
//        result(nil)
        break
        
    case "isInit":
        
        let isInit = IMClient.getInstance().isInitMars();
        result(isInit);
        break;

    case "init":
        //初始化
//        let isConsoleLogOpen = MsgUtils.toBoolValue( number: (arguments?["isConsoleLogOpen"] != nil));
//        XLogWrapper.getInstance().initXlogWrapper(isConsoleLogOpen: isConsoleLogOpen)
//
        //登录IM
        let sysConfigMap:[String:Any]  = arguments?["imConfig"] as! [String : Any];
        let paramsMap:[String:Any] = arguments?["loginParams"] as! [String : Any];
        
        let sysConfig = SysConfig.fromJsonimConfigMap(map: sysConfigMap);
        let params = InitConfigParams.fromJsonMap(map:paramsMap);
       
        //初始化成功后自动登录socket进入房间
        IMClient.getInstance().initIMClient(sysConfig: sysConfig, params: params,map:paramsMap,  result: { results in
            
//            let sysConfigMap:[String:Any]  = results as! [String : Any];
//            print("resultswk=%@",sysConfigMap);
//            result(sysConfigMap["success"]);
//           
//           
            
        }, callback: self);
    
        
        break;
        
    case  "sendMessage":
        
        print("默认调用了");

        let messageMap:[String:Any]  = arguments?["msgParams"] as! [String : Any];
        let cmdId = arguments?["cmdId"] as! Int;
        let sendTimeoutMs = arguments?["sendTimeoutMs"] as! CLong;
        let isNeedServerResp = arguments?["isNeedServerResp"] as! Bool;
        
        
        IMClient.getInstance().sendMessageNew(cmdId: cmdId, params: messageMap, sendTimeoutMs: sendTimeoutMs, isNeedServerResp: isNeedServerResp, result: { results in
            
            let sysConfigMap:[String:Any]  = results as! [String : Any];
            let code = sysConfigMap["code"] as! Int;
            print("results=%@",sysConfigMap);
//            let code = results["code"] as! Int;
            if(code == 0){
                
                
                let resultJson = sysConfigMap["resultJson"] as! String;
                let respCmdId = sysConfigMap["respCmdId"] as! Int;
                let message = sysConfigMap["message"] as! String;
                
                var msgResul = NSMutableDictionary();
                msgResul["code"] = (code);
                msgResul["message"] = message;
//                msgResul["msgId"] = "AE5CF9F484DA4CFB8C0025380AACB960";
                msgResul["respCmdId"] = respCmdId;
                msgResul["resultJson"] = resultJson;

            
                      //转data
         
                let dic = NSObjetJohn.dictionary(withJsonString: resultJson);
               
                if(dic.keys.contains("content")){
                    let contenMap = NSObjetJohn.dictionary(withJsonString: dic["content"] as! String);
                    msgResul["msgId"] = contenMap["msgId"] as? String;
                }
                
                print("dic=%@",dic);
                
             
                //说明成功了
                print("results=%@",msgResul);
                result(msgResul);
                
                
            }else{
//                let message = sysConfigMap["message"] as! String;
//                let message
                result(sysConfigMap);
            }
            
            
        }, callback: self);
        
    
        
        break;
        
    case "onReceivedMessage":
        let cmdId = arguments?["cmdId"] as! Int;
        let resultJson = arguments?["resultJson"] as! String;
        let dic = NSObjetJohn.dictionary(withJsonString: resultJson);
        print("dic=%@",dic);
        break;
        
    case "getConnectStatus":
        
        
        break;
        
    case "login":
        //登录IM
        let sysConfigMap:[String:Any]  = arguments?["sysConfig"] as! [String : Any];
        let paramsMap:[String:Any] = arguments?["loginParams"] as! [String : Any];
        
        let sysConfig = SysConfig.fromJsonMap(map: sysConfigMap);
        let params = InitConfigParams.fromJsonMap(map:paramsMap);
        
        //初始化成功后自动登录socket进入房间
        IMClient.getInstance().initIMClient(sysConfig: sysConfig, params: params, map: paramsMap, result: result, callback: self);
    
        break;
        
        
        
    case "onDestroy":
        //断开IM
        let isSuccess = IMClient.getInstance().onDestroy();
        result(isSuccess);
        break;
        
    case "sendRoomMsg":
        //房间内发送消息
        let msgContent:String = arguments?["content"] as! String;
        IMClient.getInstance().sendRoomMsg(content: msgContent, roomId: arguments?["roomId"] as! String, result: result);
        break;
        
    case "sendRoomCmd":
        //发送房间命令
        var cmdIdParams:[String:Any]  = arguments?["params"] as! [String : Any];
        let cmdId = MsgUtils.numberToIntValue(number: arguments?["cmdId"] as? NSNumber);
        
        //是否需要服务器响应
        let isNeedServerResp = MsgUtils.toBoolValue(number: (arguments?["isNeedServerResp"] != nil));
        //初始化成功后自动登录socket进入房间
        IMClient.getInstance().sendRoomCommand(cmdId: cmdId, params: cmdIdParams, isNeedServerResp: isNeedServerResp, result: result);
        break;
        
    case "enterRoom":
        //进入房间
        let isReconnect = MsgUtils.toBoolValue(number: (arguments?["isReconnect"] as! Bool));
         IMClient.getInstance().enterRoom(roomId:arguments?["roomId"] as! String, isReconnect: isReconnect, result: result);
        
        break;
        
    case "logoutRoom":
        //退出房间
        let roomId:String = arguments?["roomId"] as! String;
        IMClient.getInstance().logoutRoom(roomId: roomId, result: result);
        break;
        
    case "reconnect":
        //手动触发重连逻辑
        IMClient.getInstance().reconnect();
        result(nil);
        break;
       
        
    default:
        
        print("onMethodCall other:\(methodName)")
        result("native no define method error")
        
        break
    }
    
//    result("iOS " + UIDevice.current.systemVersion)
  }
    
    static var count = 0;
    func onReconnected() {
        print("1111---wwwwwww");
        SwiftImPlugin_new.count+=1;
        var dict = NSMutableDictionary();
        dict["reconnectedCount"] = (SwiftImPlugin_new.count);
        
        invokeMethod(method: "onReconnected",arguments:dict);
    }
    
    func onLoginSuccess(){
        var dict = NSMutableDictionary();
        invokeMethod(method: "onLoginSuccess",arguments:dict);
    }
    
    func onLoginFail(respId:Int,initConfigParams:InitConfigParams){
        var dict = NSMutableDictionary();
        if(respId != nil){
            dict["loginRespId"] = respId;
        }
        
        if(initConfigParams != nil){
            dict["respJson"] = initConfigParams;
        }
       
        
        invokeMethod(method: "onLoginFail",arguments:dict);
    }
    
    
    
    func onReceivedMsg(roomId: String, cmdId: Int, contentJson: String) {
        
        var map:[String:Any] = [String:Any].init()
        map["messageJson"] = contentJson;
        map["roomId"] = roomId;
        map["cmdId"] = cmdId;
        invokeMethod(method: "onReceivedMessage", arguments: map);
        
    }
    
}
